package com.ks.winterwarmimage;

import android.content.ContentValues;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListPopupWindow;
import android.widget.TextView;

import com.ks.winterwarmimage.adapter.AccountAdapter;
import com.ks.winterwarmimage.database.DatabaseManager;
import com.ks.winterwarmimage.esptouch.EspTouchManage;
import com.ks.winterwarmimage.mqtt.MqttMag;
import com.ks.winterwarmimage.mqtt.MsgMqttService;
import com.ks.winterwarmimage.utils.BasicsUtil;
import com.ks.winterwarmimage.utils.CmdDataPacket;
import com.ks.winterwarmimage.utils.Constants;
import com.ks.winterwarmimage.wifi.WiFiTools;

import java.util.ArrayList;
import java.util.List;

public class UpdateAccountActivity extends BaseActivity implements View.OnClickListener{
    private static final String TAG ="UpdateAccountActivity";
    private static final String base_topic="WinterWarmImage/dev/";
    private TextView textTitle,textDevId,textOldAccount,textNewAccount,textUpdateState;
    private String deviceId=null;
    private String newAccount=null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_account);
        textTitle = findViewById(R.id.text_title);
        textTitle.setText(R.string.update_account);
        textDevId = findViewById(R.id.text_dev_id);
        textOldAccount = findViewById(R.id.text_old_account);
        textNewAccount = findViewById(R.id.text_new_account);
        textUpdateState=findViewById(R.id.text_update_state);
        Bundle bundle=this.getIntent().getExtras();
        if(bundle!=null){
            if(bundle.containsKey(Constants.KEY_MAC_ID)) {
                deviceId = this.getIntent().getStringExtra(Constants.KEY_MAC_ID);
                textDevId.setText(deviceId.toUpperCase());
            }
            if(bundle.containsKey(Constants.KEY_ACCOUNT_ID)) {
                textOldAccount.setText(this.getIntent().getStringExtra(Constants.KEY_ACCOUNT_ID));
            }
        }
        findViewById(R.id.img_return).setOnClickListener(this);
        findViewById(R.id.linear_account_select).setOnClickListener(this);
        if(deviceId!=null) {
            findViewById(R.id.btn_update).setOnClickListener(this);
            this.bindMqttService();
        }
    }

    @Override
    protected void onDestroy() {
        if(deviceId!=null) {
            unMqttBroadcastReceiver();
        }
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            Log.e(TAG,"按下Back或Home键退出");
            finishResult();
        }
        return super.onKeyDown(keyCode, event);
    }
    @Override
    public void onClick(View view) {
        if(view.getId()==R.id.img_return){
            finishResult();
        }else if (view.getId()==R.id.linear_account_select){
            showListPopup(view);
        }else if(view.getId()==R.id.btn_update){
            if(deviceId!=null){
                String accountId=textNewAccount.getText().toString();
                //if(accountId==null || accountId.equalsIgnoreCase(textOldAccount.getText().toString())){
                //    textUpdateState.setText(R.string.same_without_updates);
               // }else {
                    if (accountId.getBytes(EspTouchManage.GB2312).length < 8) {
                        textUpdateState.setText(R.string.insufficient_len);
                    } else if (accountId.getBytes(EspTouchManage.GB2312).length > 8) {
                        textUpdateState.setText(R.string.update_len_exceed);
                    } else {
                        textUpdateState.setText(R.string.update_start);
                        byte[] send_bytes = accountId.getBytes(EspTouchManage.GB2312);  //将账号ID转为字节数组
                        CmdDataPacket dataPacket = new CmdDataPacket(CmdDataPacket.CMD_UPDATE_ACCOUNT_ID,  send_bytes);
                        String id = BasicsUtil.removeMacColon(deviceId).toUpperCase();    //去除冒号
                        String topic = "WinterWarmImage/phone/" + id;
                        MsgMqttService.publish(topic, dataPacket.toBytes(), 0, false);
                    }
                }
           // }
        }
    }

    @Override
    protected void onMessageArrived(MqttMag message) {
        super.onMessageArrived(message);
        String topic = message.getTopic().replace(base_topic, "");  //去掉基主题部分
        String id= BasicsUtil.removeMacColon(deviceId);    //去除冒号
        if(id.equalsIgnoreCase(topic)) {    //收到的消息和设备号一致
            receiveAnalysis(message.getMessage(), deviceId);
        }
    }
    /**
     * 完成返回
     */
    private void finishResult(){
        if(newAccount!=null && newAccount.length()==8){
            Intent intent=new Intent();
            intent.putExtra(Constants.KEY_MAC_ID,deviceId);
            intent.putExtra(Constants.KEY_ACCOUNT_ID,newAccount);
            setResult(RESULT_CODE+3,intent);
        }
        finish();
    }
    /**
     * 解析接收到的数据
     * @param data 接收到的数据
     * @param mac_id 设备号
     */
    private void receiveAnalysis(byte[] data,String mac_id) {
        if(mac_id!=null){
            CmdDataPacket cmdDataPacket = CmdDataPacket.fromBytes(data);  //将消息转为标准命令结构
            if(cmdDataPacket!=null && cmdDataPacket.command==CmdDataPacket.CMD_UPDATE_ACCOUNT_ID_ACK){
                StringBuffer sb = new StringBuffer(textUpdateState.getText());
                sb.append("\n");
                if(cmdDataPacket.data[0]==1){
                    //更新成功
                    sb.append(getString(R.string.update_ok));
                    updateAccount(mac_id,textNewAccount.getText().toString());
                }else{
                    //更新失败
                    sb.append(getString(R.string.update_fail));
                }
                textUpdateState.setText(sb);
            }
        }
    }
    /**
     * 更新数据库中的账号
     * @param mac_id 设备号
     * @param account 新的账号
     */
    private void updateAccount(String mac_id,String account){
        ContentValues values=new ContentValues();
        values.put(Constants.KEY_ACCOUNT_ID,account);
        int count= DatabaseManager.database.update(Constants.TABLE_DEV,values,Constants.KEY_MAC_ID+"=?",new String[]{mac_id.toLowerCase()});
        StringBuffer sb = new StringBuffer(textUpdateState.getText());
        sb.append("\n");
        if(count>0){
            sb.append(getString(R.string.update_local_ok));
        }else{
            sb.append(getString(R.string.update_local_fail));
        }
        textUpdateState.setText(sb);
        newAccount=account;
    }
    private void showListPopup(View v) {
        AccountAdapter adapterAccount;
        List<AccountAdapter.Account> accountList=new ArrayList<>();
        List<String> accountIds= DatabaseManager.getAccountList();
        if(accountIds!=null && accountIds.size()>0){
            for(int i=0;i<accountIds.size();i++){
                AccountAdapter.Account account=new AccountAdapter.Account(accountIds.get(i),false);
                if(account.accountId.equalsIgnoreCase(textNewAccount.getText().toString())){
                    account.isSelected=true;
                }
                accountList.add(account);
            }
        }else{
            AccountAdapter.Account account=new AccountAdapter.Account(getString(R.string.no_account),false);
            accountList.add(account);
        }
        adapterAccount=new AccountAdapter(this,accountList,true);
        ListPopupWindow listPopupWindow=new ListPopupWindow(this);
        listPopupWindow.setBackgroundDrawable(getDrawable(R.drawable.rounded_corners));
        listPopupWindow.setAnchorView(v);//设置ListPopupWindow的锚点，关联mButton位置
        listPopupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT); //设置宽度
        listPopupWindow.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
        //listPopupWindow.setHorizontalOffset(10);
        listPopupWindow.setVerticalOffset(5);
        listPopupWindow.setModal(true);
        listPopupWindow.setAdapter(adapterAccount);
        listPopupWindow.setOnItemClickListener((parent, view, position, id)->{
            textNewAccount.setText(accountList.get(position).accountId);
            listPopupWindow.dismiss();
        });
        listPopupWindow.show();
    }
}